package sk.pitonak.mhd.ui;

import java.util.ArrayList;

import sk.pitonak.mhd.Database;
import sk.pitonak.mhd.R;
import sk.pitonak.mhd.Result;
import sk.pitonak.mhd.U;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.Window;

public class ResultActivity extends SherlockActivity {
	private static final int MENU_MAP = 0;
	
	private static final int MESSAGE_SHOW_RESULTS = 0;
	private static final int MESSAGE_STOP_LOADING = 1;

	private Thread mBackgrounThread;

	private boolean mLoading = false;

	private ViewPager mViewPager;
	private ResultPagerAdapter mPagerAdapter;
	private ArrayList<Result> mResults;

	private static Bundle sBundle;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

		setContentView(R.layout.activity_results);
		setProgressBarIndeterminateVisibility(Boolean.FALSE);

		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		mPagerAdapter = new ResultPagerAdapter();

		mViewPager = (ViewPager) findViewById(R.id.pager);
		mViewPager.setAdapter(mPagerAdapter);

		Bundle bundle = getIntent().getExtras();
		// TODO: orientation change?
		getResults(bundle);
	}
	
	@Override
	protected void onDestroy() {
		if(mBackgrounThread != null) mBackgrounThread.interrupt();
		super.onDestroy();
	}

	private void getResults(Bundle bundle) {
		startLoading();

		sBundle = bundle;

		final String from = sBundle.getString(SearchFragment.KEY_FROM);
		final String to = sBundle.getString(SearchFragment.KEY_TO);
		String _time = sBundle.getString(SearchFragment.KEY_TIME);
		String _date = sBundle.getString(SearchFragment.KEY_DATE);
		
		// TODO: seriously?
		Database database = new Database(this);
		database.addToHistory(from, to);
		database.close();
		
		if(_time == null || _date == null) {
			int[] date = U.getCurrentTimeAndDate();
			_time = U.getTimeString(date[0], date[1]);
			_date = U.getDateString(date[4], date[3], date[2]);
		}
		
		final String time = _time;
		final String date = _date;

		mBackgrounThread = U.performOnBackgroundThread(new Runnable() {
			@Override
			public void run() {
				try {
					// TODO: remove dummy
					if(U.DEBUG) {
						mResults = U.getDummyResults(ResultActivity.this);
					}
					else {
						mResults = U.getOnlineResults(from, to, time, date);
					}
					mHandler.sendEmptyMessage(MESSAGE_SHOW_RESULTS);
				}
				catch(Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(MESSAGE_STOP_LOADING);
			}
		});
	}

	private void showResults() {
		if(mResults == null) return;
		mPagerAdapter.setResults(mResults);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		menu.add(0, MENU_MAP, 0, R.string.map)
//			.setIcon(R.drawable.ic_menu_mapmode)
//			.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
			case android.R.id.home:
				finish();
				return true;
			case MENU_MAP:
				// TODO: mapview
				Toast.makeText(this, "mapa", Toast.LENGTH_SHORT).show();
				return true;
			default:
				return super.onOptionsItemSelected(item);
		}
	}

	private void startLoading() {
		if(mLoading) return;
		setSupportProgressBarIndeterminateVisibility(true);
		mLoading = true;
	}

	private void stopLoading() {
		if(!mLoading) return;
		setSupportProgressBarIndeterminateVisibility(false);
		mLoading = false;
	}
	
	private Handler mHandler = new Handler(new Handler.Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			switch(msg.what) {
				case MESSAGE_SHOW_RESULTS:
					showResults();
					break;
				case MESSAGE_STOP_LOADING:
					stopLoading();
					break;
			}
			return true;
		}
	});
	
	private class ResultPagerAdapter extends PagerAdapter {
		public void setResults(ArrayList<Result> results) {
			mResults = results;
			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			if(mResults == null) return 0;
			return mResults.size();
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			View view = mResults.get(position).getView(ResultActivity.this);
			container.addView(view);
			return view;
		}
		
		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}
		
		@Override
		public boolean isViewFromObject(View view, Object object) {
			return object == view;
		}
	}
}
